import pandas as pd
import numpy as np
import os
dir = r"D:\data_cmp\airfoil_csv"

def check_leading_trailing(file):
    df = pd.read_csv(file)
    x = df['x'].to_numpy()
    y = df['y'].to_numpy()

    def fmin(x):
        return np.argwhere(x == np.min(x)).flatten()

    leading = fmin(x.flatten())
    trailing = []
    trailing.append(np.argmax(x.flatten()[0:leading[0]]))
    trailing.append(np.argmax(x.flatten()[leading[0]+1::]))
    trailing = np.asarray(trailing)

    return ((leading.shape == 1, x[leading] == 0, y[leading] == 0, x[leading], y[leading], leading),
            (trailing.shape[0] == 2, x[trailing] == 1, y[trailing] == 0, x[trailing], y[trailing], trailing))


def check_dataset_leading_trailing(f):
    count = 0
    read_dir = r"D:\data_cmp\airfoil_csv_op\airfoil_csv_op_4_clip"
    save_dir = r"D:\data_cmp\airfoil_csv_op\airfoil_csv_op_5_clip"

    count0 = 0
    count1 = 0
    count2 = 0
    leading_y = []
    count3 = 0
    count4 = 0
    count5 = 0

    for file in os.listdir(read_dir):
        file_path = os.path.join(read_dir, file)
        leading, trailing = f(file_path)
        count0 += (False == leading[0])
        count1 += (False == leading[1].any())
        count2 += (False == leading[2].any())
        count3 += (False == trailing[0])
        count4 += (False == trailing[1].any())
        count5 += (False == trailing[2].any())
        count += 1
        if not leading[1].any():
            print("x is not 0", leading[3], leading[4], file)
        if not leading[2].any():
            print("y is not 0", leading[3], leading[4], file)
            leading_y += list(abs(leading[4]))
        if not trailing[0]:
            print("shape is not 2:", trailing[3], trailing[4], file)
            save_path = os.path.join(save_dir, file)
        if not trailing[1].any():
            print("x is not 1:", trailing[3], trailing[4], file)
            save_path = os.path.join(save_dir, file)
        if not trailing[2].any():
            print("y is not 0:", trailing[3], trailing[4], file)

    leading_y = np.asarray(leading_y).flat

    print("翼型总数：", count)
    print("x为0的坐标的个数不为1的个数：", count0)
    print("前缘x坐标不为0，需要归一化：", count1)
    print("前缘y坐标不为0，需要平移：", count2)
    print("后缘不为2个点的个数：", count3)
    print("后缘x坐标不为1的个数，需要归一化：", count4)
    print("后缘y坐标不为0的个数，需要旋转：", count5)


def __check_seq(file, isequal):
    df = pd.read_csv(file)
    x = df['x']
    y = df['y']

    i = 0
    n = x.shape[0]
    if isequal is False:
        while (i < n - 1 and x[i] > x[i + 1]):
            i += 1
        while (i < n - 1 and x[i] < x[i + 1]):
            i += 1
    else:
        while (i < n - 1 and x[i] >= x[i + 1]):
            i += 1
        while (i < n - 1 and x[i] <= x[i + 1]):
            i += 1

    if i == n - 1:
        return True
    else:
        return False


def __find_dataset_abSeq(read_dir):
    not_in_order = []

    print("以下为不按逆时针排列的翼型数据：")
    for file in os.listdir(read_dir):
        file_path = os.path.join(read_dir, file)
        res = __check_seq(file_path, True)
        if res is False:
            print(file_path)
            not_in_order.append(file)
    print()

    return not_in_order


def __transform(ordinate):
    stack = []
    x = ordinate[:, 0]
    mid = np.argmax(x)
    for i in range(mid, -1, -1):
        stack.append(x[i])
    for i in range(0, mid + 1):
        x[i] = stack[i]
    ordinate[:, 0] = x

    return ordinate

def transform_anti_clockwise(read_dir, save_dir):
    file_set = __find_dataset_abSeq(read_dir)
    for file in file_set:
        save_path = os.path.join(save_dir, file)
        ordinates = pd.read_csv(os.path.join(read_dir, file)).to_numpy()
        tran_ordinates = __transform(ordinates)
        df = pd.DataFrame(tran_ordinates)
        df.columns = ["x", "y"]
        df.to_csv(save_path, index=False)


def Detecting_Monotonicity(file_dir):
    for file in os.listdir(file_dir):
        file_path = os.path.join(file_dir, file)
        ordinates = pd.read_csv(file_path, index_col=None, header=0).to_numpy()
        nums = ordinates.shape[0] // 2

        up = ordinates[0:nums, 1][::-1]
        up_20 = np.argmax(up)
        flag = True
        for i in range(up_20 - 1):
            if up[i] > up[i + 1]:
                print("{} {} {}".format(i, up[i], up[i + 1]))
                flag = False
                break
        if flag == False:
            print("{} head 0.2 error".format(file))

        flag = True
        for i in range(up_20 + 1, nums - 1):
            if up[i] < up[i + 1]:
                print("{} {} {}".format(i, up[i], up[i + 1]))
                flag = False
                break
        if flag == False:
            print("{} head 0.8 error".format(file))

        low = ordinates[nums + 1::, 1]
        low_20 = np.where(ordinates[nums + 1::, 0] < 0.1)[0]
        flag = True
        for i in range(len(low_20) - 1):
            if low[low_20[i]] < low[low_20[i + 1]]:
                flag = False
                break
        if flag == False:
            print("{} tail 0.2 error".format(file))

        low_80 = np.where(ordinates[nums + 1::, 0] > 1 - 0.2)[0]
        flag = True
        for i in range(len(low_80) - 1):
            if low[low_80[i]] > low[low_80[i + 1]]:
                flag = False
                break
        if flag == False:
            print("{} tail 0.8 error".format(file))
